package cn.t222.service;

import cn.t222.config.mq.OrderCancelSender;
import cn.t222.config.mq.RabbitConfig;
import cn.t222.mapper.OrderMapper;
import cn.t222.pojo.ItripHotelOrder;
import cn.t222.pojo.StoreVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class OrderService {
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private OrderCancelSender orderCancelSender;

    public List<StoreVO> queryRoomStore(Map<String,Object> params) {
        return orderMapper.queryRoomStore(params);
    }
    public void flushStore(Map<String,Object> params) {
        orderMapper.flushStore(params);
    }

    public void add(ItripHotelOrder order) {
        orderMapper.add(order);
    }

    public boolean update(ItripHotelOrder order) {
        return orderMapper.update(order)==1;
    }

    public ItripHotelOrder get(Long id) {
        return orderMapper.get(id);
    }

    public ItripHotelOrder getByNo(String no) {
        return orderMapper.getByNo(no);
    }

    @Transactional
    public String createOrder(ItripHotelOrder order) {
        Map<String, Object> params = new HashMap<>();
        params.put("startTime", order.getCheckInDate());
        params.put("endTime", order.getCheckOutDate());
        params.put("hotelId", order.getHotelId());
        params.put("roomId", order.getRoomId());
        flushStore(params);
        List<StoreVO> list = this.queryRoomStore(params);
        int bookingDays = order.getBookingDays();
        for (StoreVO vo : list) {
            if(vo.getStore() < bookingDays) {
                return vo.getStore() + ":库存不足:"+bookingDays + ":" + format(vo.getDate());
            }
        }
        order.setOrderNo(UUID.randomUUID().toString());
        this.add(order);
        //发送延迟取消订单消息
        orderCancelSender.send(RabbitConfig.QUEUE_ORDER_CANCEL,order.getOrderNo());
        return "success";
    }

    public String format(Date date) {
        if(date == null) return "";
        return new SimpleDateFormat("yyyy.MM.dd").format(date);
    }
}
